<script setup>
import { ref, defineEmits } from 'vue'
import {
  getUserInfoApi,
  updateUserInfoApi,
  updatePwdApi
} from '@/apis/admin-user'
import { useUserStore } from '@/stores'
import router from '@/router'
import { Plus } from '@element-plus/icons-vue'
import { uploadFileApi } from '@/apis/common.js'

const emit = defineEmits(['title'])
emit('title', '我的信息')
const userStore = useUserStore()
const formData = ref({
  id: 0,
  nickName: '',
  gender: '',
  phone: ''
})

// 获取用户数据
const getUserInfo = async () => {
  const res = await getUserInfoApi(0)
  formData.value = res.data.data
}
getUserInfo()

// 修改用户信息
const formRef = ref(null)
const formRules = {
  nickName: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称需要 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    {
      pattern: /^1[3456789]\d{9}$/,
      message: '手机号码格式不正确',
      trigger: 'blur'
    }
  ],
  gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }]
}

const selectGender = (e) => {
  formData.value.gender = e
}

const updateUserInfo = async () => {
  await formRef.value.validate()
  console.log(formData.value)

  await updateUserInfoApi(formData.value)
  ElMessage({
    message: '修改成功',
    type: 'success'
  })
  // 重新获取数据
  getUserInfo()
  userStore.setUserInfo(formData.value)
}

// 修改密码
const pwdData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const pwdRef = ref(null)
const pwdRules = {
  oldPassword: [
    { required: true, message: '旧密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '旧密码需要 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '新密码需要 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      min: 6,
      max: 20,
      message: '确认密码需要 6 到 20 个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdData.value.newPassword) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      }
    }
  ]
}

const updateUserPwd = async () => {
  await pwdRef.value.validate()
  await updatePwdApi(pwdData.value)
  ElMessage({
    message: '修改成功',
    type: 'success'
  })
  //  清空 pinia 存储
  userStore.setToken('')
  userStore.setUserInfo(null)
  setTimeout(() => {
    router.replace({
      path: '/login'
    })
  }, 1500)
  // 返回登录页
}

// 头像

const imgUrl = ref('')
const onUpload = async (uploadFile) => {
  imgUrl.value = ''
  // console.log(uploadFile) // uploadFile.raw 就可以获取到上传的文件对象了
  // URL.createObjectURL(文件对象)  可以返回一个可供本地预览的文件地址
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  // 将文件对象赋值给 formModel 作为请求数据
  const fileData = new FormData()
  fileData.append('file', uploadFile.raw)
  // console.log(formData)
  const res = await uploadFileApi(fileData)
  formData.value.avatar = res.data.data
}
</script>

<template>
  <div class="page">
    <!-- 修改信息 -->
    <el-card class="update-info">
      <template #header>
        <span class="card-title">修改信息</span>
      </template>
      <el-row>
        <el-col :span="8">
          <div class="info-box">
            <el-form
              ref="formRef"
              style="max-width: 18rem"
              :model="formData"
              :rules="formRules"
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item label="用户名">
                <el-input v-model="formData.username" disabled />
              </el-form-item>
              <el-form-item label="昵称：" prop="nickName">
                <el-input v-model="formData.nickName" autocomplete="off" />
              </el-form-item>
              <el-form-item label="手机号码：" prop="phone">
                <el-input v-model="formData.phone" autocomplete="off" />
              </el-form-item>
              <el-form-item label="性别：" prop="gender">
                <el-radio-group
                  v-model="formData.gender"
                  @change="selectGender"
                >
                  <el-radio :value="1" size="large">男</el-radio>
                  <el-radio :value="2" size="large">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
            <div class="but-box">
              <el-button type="danger" @click="updateUserInfo"
                >确定修改</el-button
              >
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <el-form-item label="头像：">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="onUpload"
            >
              <img
                v-if="formData.avatar"
                :src="formData.avatar"
                class="avatar"
                alt=""
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
    <!-- 修改密码 -->
    <el-card class="update-pwd">
      <template #header>
        <span class="card-title">修改密码</span>
      </template>
      <div>
        <el-form
          ref="pwdRef"
          style="max-width: 18rem"
          :model="pwdData"
          :rules="pwdRules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="旧密码：" prop="oldPassword">
            <el-input
              v-model="pwdData.oldPassword"
              autocomplete="off"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码：" prop="newPassword">
            <el-input
              v-model="pwdData.newPassword"
              autocomplete="off"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确定密码：" prop="confirmPassword">
            <el-input
              v-model="pwdData.confirmPassword"
              autocomplete="off"
              type="password"
              show-password
            />
          </el-form-item>
        </el-form>
        <div class="but-box">
          <el-button type="danger" @click="updateUserPwd">确定修改</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.page {
  .but-box {
    width: 15rem;
    display: flex;
    justify-content: center;
  }

  .update-info {
    margin: 1rem 2rem;
  }

  .update-pwd {
    margin: 0 2rem;
  }
}

/* 文件上传样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 6.25rem;
      height: 6.25rem;
      text-align: center;
    }
  }
}
</style>
